import sys
import os

from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, ".."))
sys.path.append(os.path.join(thisDir, "..", "ps"))
sys.path.append(os.path.join(thisDir, "..", "..", "common"))

import SessionManager
import EJOConst

from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

class EJOGetBill(EJOHandlerBase):
    def _doHandle(self):
        logger.debug(f"Handled by: {__name__}")

        startDate = self._convertToDateObj(self._getParamValue("from"))
        endDate = self._convertToDateObj(self._getParamValue("to"))
        if startDate == None or endDate == None or endDate < startDate:
            return True, HTTPStatus.BAD_REQUEST, "Bad date param"

        session = self._getParamValue("session")
        fid = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_FAMILY_ID, session)

        sql = "select " + \
            "bill.Datetime as datetime, bill.Amount as amount, bill.Currency as currencyID, bill.Note as note," + \
            "person.Name as owner," + \
            "currency.Name as currency," + \
            "paymentmode.Name as paymentmode," + \
            "billcategory.Name as category" + \
            " from " + \
            "bill, currency, paymentmode, billcategory, person" + \
            " where " + \
            "bill.Datetime >= '" + self._getParamValue("from") + "' and bill.Datetime <= '" + self._getParamValue("to") + "'" + \
            " and " + \
            "bill.PID = person.ID" + \
            " and " + \
            "bill.Currency = currency.ID" + \
            " and " + \
            "bill.PaymentMode = paymentmode.ID" + \
            " and " + \
            "bill.Category = billcategory.ID" + \
            " and " + \
            "bill.PID in (select person.ID from person where person.FID=" + str(fid) + ")" + \
            " order by bill.Datetime asc"

        db = SessionManager.SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
        result = []
        for row in db.Execute(sql):
            outputDate = row[0].split()[0]
            amount = row[1]
            note = row[3]
            owner = row[4]
            currency = row[5]
            payment = row[6]
            category = row[7]
            result.append([owner, outputDate, amount, currency, category, payment, note])

        return True, HTTPStatus.OK, str(result)

